package com.steam.splace;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import thread.DoThreadGet;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import bo.DirectionsJSONParser;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.Circle;
import com.google.android.gms.maps.model.CircleOptions;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;
import com.google.gson.Gson;

import dao.DataAccess;
import entity.Category;

public class SearchByAreaActivity extends FragmentActivity implements
		LocationListener {
	ArrayAdapter<String> adapter;
	GoogleMap googleMap;
	int positionOnSpin = -1;
	int positionOnSpinCat = -1;
	ArrayList<String> dataCat;
	ArrayList<LatLng> markerPoints;
    private final int searchplacezone_tag = 18;
	private final int getfavorite_tag = 9;
	HashMap<String, String> plids;
	float zoomlevel=12;
	Handler handler;
	Location location ;
	Intent pIntent;
	double longitude,latitude;
	Activity currentActivity;
	Spinner spPlaceType,spCategory;
	int uid=-1;
	Button bt;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.searcharea_activity);
		currentActivity=this;
		spCategory=(Spinner)this.findViewById(R.id.spCategory);
		spPlaceType=(Spinner)this.findViewById(R.id.spPlaceType);
		ArrayList<String> list=new ArrayList<String>();
		list.add("1 km");
		list.add("2 km");
		list.add("3 km");
		list.add("5 km");
		list.add("10 km");
		ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, list);
			dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			spPlaceType.setAdapter(dataAdapter);
			spPlaceType.setOnItemSelectedListener(new MyEvent());
		bt = (Button) this.findViewById(R.id.btOpenAddPlaceActivity);
		//uid=getUID();
		fillCategory();
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
		uid = prefs.getInt("uid", -1);
		if (uid == -1) {
		bt.setVisibility(View.GONE);
		}

				
		markerPoints = new ArrayList<LatLng>();

		// Showing status
		// Google Play Services are available

		// Getting reference to the SupportMapFragment of activity_main.xml
		SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager()
				.findFragmentById(R.id.map);

		// Getting GoogleMap object from the fragment
		googleMap = fm.getMap();

		//CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(
		//		new LatLng(21.076591538593824, 105.79306125640869), zoomlevel);
		//googleMap.animateCamera(cameraUpdate);
		// Enabling MyLocation Layer of Google Map
		googleMap.setMyLocationEnabled(true);
		pIntent = new Intent(this, ViewPlaceActivity.class);
		googleMap.setOnMarkerClickListener(new OnMarkerClickListener() {

			@Override
			public boolean onMarkerClick(Marker marker) {

				// System.out.println("mID"+marker.getId());
				// System.out.println(plids.get(marker.getId()));
				marker.showInfoWindow();
				return true;
			}
		});
		googleMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {          
            public void onInfoWindowClick(Marker marker) 
            {
				pIntent.putExtra("pid",
						Integer.parseInt(plids.get(marker.getId())));
				Log.d("place id", Integer.parseInt(plids.get(marker.getId()))
						+ "");
				startActivity(pIntent);
            }
            });
		LocationManager locationmanager = (LocationManager) getSystemService(LOCATION_SERVICE);
        Criteria cr = new Criteria();
        String provider = locationmanager.getBestProvider(cr, true);
        location = locationmanager.getLastKnownLocation(provider);
      if (location != null) {
				 //onLocationChanged(location);
				 //locationmanager.requestLocationUpdates(provider, 20000, 0, this);
				 //location = locationmanager.getLastKnownLocation(provider);
            double lat=location.getLatitude();
        double lng=location.getLongitude();
        
		Log.v("my location",lat+"/"+lng);
        }
      locationmanager.requestLocationUpdates(provider, 20000, 0, this);
        googleMap.setOnMapClickListener(new OnMapClickListener() {
			@Override
			public void onMapClick(LatLng point) {
				googleMap.clear();
				longitude=point.longitude;
				latitude=point.latitude;
    			List<NameValuePair> params = new ArrayList<NameValuePair>();
    			params.add(new BasicNameValuePair("placename",""));
    			params.add(new BasicNameValuePair("longitude", longitude+""));
    			params.add(new BasicNameValuePair("latitude", latitude+""));
    			params.add(new BasicNameValuePair("categoryid",((Category) (spCategory.getSelectedItem())).getCategoryid()+""));
    			double radius=0;
    			
    			/*Marker marker = googleMap.addMarker(new MarkerOptions()
				.position(new LatLng(latitude, longitude)));
    			
    			Marker marker1 = googleMap.addMarker(new MarkerOptions()
				.position(new LatLng(latitude+0.1, longitude)));
    			
    			Marker marker2 = googleMap.addMarker(new MarkerOptions()
				.position(new LatLng(latitude-0.1, longitude)));

    			Marker marker3 = googleMap.addMarker(new MarkerOptions()
				.position(new LatLng(latitude, longitude+0.1)));
    			
    			Marker marker4 = googleMap.addMarker(new MarkerOptions()
				.position(new LatLng(latitude, longitude-0.1)));
    			*/
    			
    			if(positionOnSpin==0)
    				radius=1;
    			else if(positionOnSpin==1)
    				radius=2;
    			else if(positionOnSpin==2)
    				radius=3;
    			else if(positionOnSpin==3)
    				radius=5;
    			else
    				radius=10;

				DoThreadGet sp = new DoThreadGet(currentActivity);
    			params.add(new BasicNameValuePair("radius", radius+""));

    			Circle circle = googleMap.addCircle(new CircleOptions()
			     .center(new LatLng(latitude, longitude))
			     .radius(radius*1000)
			     .strokeColor(Color.RED)
			     .fillColor(0x44ff0000));
    			
    			ArrayList l = new ArrayList();
				plids=new HashMap<String, String>();
			l.add(searchplacezone_tag);
			l.add(params);
			l.add(googleMap);
			l.add(plids);
			sp.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR,l);
				}
			});

	}
	

	public void onClick(View view) {
		int id = view.getId();
		if (id == R.id.btOpenAddPlaceActivity) {
			Intent addPlaceIntent = new Intent(this, AddPlaceActivity.class);
			startActivity(addPlaceIntent);
		} else if (id == R.id.btFind) {
		}
	}


	private void fillCategory() {
		ArrayList<Category>cat=new ArrayList<Category>();
		Category tmp=new Category(0, "Danh mục", "Danh mục", 0);
		cat.add(tmp);
		  Gson gson = new Gson();
		  SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
		    int catSize = prefs.getInt("categorysize", 0);		    
		    for(int i=0;i<catSize;i++){
		    	String json = prefs.getString("category_"+i, "");
		    	cat.add(gson.fromJson(json, Category.class));
		    }
		if(cat!=null){
			ArrayAdapter<Category> adapter=new ArrayAdapter<Category>
			 (this,
			 android.R.layout.simple_spinner_item,
			 cat
			 );
			adapter.setDropDownViewResource
			 (android.R.layout.simple_list_item_single_choice);
			Spinner spCategory=(Spinner)this.findViewById(R.id.spCategory);
			spCategory.setAdapter(adapter);
		}
		spCategory.setOnItemSelectedListener(new MyEvent2());
	}


	@Override
	public void onLocationChanged(Location location) {

		// Getting latitude of the current location
		this.location.setLongitude(location.getLongitude());
		this.location.setLatitude(location.getLatitude());

		// Showing the current location in Google Map
		googleMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng( location.getLatitude(),location.getLongitude())));

		// Zoom in the Google Map
		googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));

	}
public int getUID(){
	
	DoThreadGet thread1 = new DoThreadGet(this);
	ArrayList params1 = new ArrayList();
	params1.add(getfavorite_tag);
	DataAccess da = new DataAccess(this);
	int uid = -1;
	try {
		da.open();
		if (da.getUserInUse() != null)
			uid = da.getUserInUse().getId();
		else
			uid = -1;

	} catch (SQLException e) {
		// TODO Auto-generated catch block
		// e.printStackTrace();
		uid = -1;
	} finally {
		da.close();
	}
	return uid;
}
	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub
	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		//getMenuInflater().inflate(R.menu.main, menu);

		//this.menu=menu;
		//uid=getUID();
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
		uid = prefs.getInt("uid", -1);
		if(uid!=-1){
			getMenuInflater().inflate(R.menu.main, menu);}
		else getMenuInflater().inflate(R.menu.menunologin, menu);
		return true;
	}
	private class MyEvent implements OnItemSelectedListener {

		@Override
		public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			// TODO Auto-generated method stub
			positionOnSpin = arg2;
			Log.v("position",arg2+"");
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub

		}

	}
	private class MyEvent2 implements OnItemSelectedListener {

		@Override
		public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			// TODO Auto-generated method stub
			positionOnSpinCat = arg2;
			Log.v("position",arg2+"");
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub

		}

	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		if (item.getItemId() == R.id.menuSearch) {
			if (!this.getClass().getSimpleName().equals("SearchActivity")) {
				Intent searchIntent = new Intent(this, SearchActivity.class);
				startActivity(searchIntent);
			}
		} else if (item.getItemId() == R.id.menuProfile) {
			if (!this.getClass().getSimpleName().equals("ProfileActivity")) {
				Intent profileIntent = new Intent(this, ProfileActivity.class);
				startActivity(profileIntent);
			}
		}
		else if(item.getItemId() == R.id.SignOut){
			DataAccess da=new DataAccess(this);
			try {
				da.open();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			da.signOut();
			da.close();
			SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
			Editor prefsEditor = prefs.edit(); 
			prefsEditor.putInt("uid", -1);
			prefsEditor.putString("token", "");
				prefsEditor.commit();
			this.finish();
			Intent loginIntent = new Intent(this, MainActivity.class);
			startActivity(loginIntent);
		}
		else if(item.getItemId() == R.id.menuSignUp){
			if (!this.getClass().getSimpleName().equals("SignUpActivity")) {

				Intent signUpActivity = new Intent(this, SignUpActivity.class);
				startActivity(signUpActivity);
			}
		}
		else if(item.getItemId() == R.id.menuForgot){
			if (!this.getClass().getSimpleName().equals("ForgotPasswordActivity")) {
				Intent forgotPasswordActivity = new Intent(this, ForgotPasswordActivity.class);
				startActivity(forgotPasswordActivity);
			}
		}
		else if(item.getItemId() == R.id.menuAddPlace){
			if (!this.getClass().getSimpleName().equals("AddPlaceActivity")) {
				Intent addPlaceActivity = new Intent(this, AddPlaceActivity.class);
				startActivity(addPlaceActivity);
			}
		}
		else if(item.getItemId() == R.id.menuSignIn){
			if (!this.getClass().getSimpleName().equals("MainActivity")) {
				Intent mainActivity = new Intent(this, MainActivity.class);
				startActivity(mainActivity);
			}
		}
		else if(item.getItemId() == R.id.menuSearchArea){
			if (!this.getClass().getSimpleName().equals("SearchByAreaActivity")) {
				Intent menuSearchArea = new Intent(this, SearchByAreaActivity.class);
				startActivity(menuSearchArea);
			}
		}
		else if(item.getItemId() == R.id.menuFavorite){
			if (!this.getClass().getSimpleName().equals("FavoriteActivity")) {

				Intent favoriteActivity = new Intent(this, FavoriteActivity.class);
				startActivity(favoriteActivity);
			}
		}

		return true;
	}
}
